<?php
namespace app\admin\model;

use app\common\model\User as UserModel;
use think\facade\Session;
use think\facade\Db;

/**
 * 用户模型
 */
class User extends UserModel
{
     /**
     * 管理员用户登录
     */
    public function login(array $data)
    {
        if(!captcha_check($data['captcha'])){
            $this->error = '验证码错误';
            return false;
        }
        //体验用户
        if($data['user_name'] =='test' AND $data['password']=='test'){
            // 保存登录状态
            Session::set('hema_admin', [
                'user' => [
                    'user_name' => 'test',
                    'avatar' => base_url() . 'assets/img/avatar.png'
                ],
                'is_login' => true,
            ]);
            return true;
        }
        $filter = [
            'user_name' => $data['user_name'],
            'status' => 10
        ];
        // 验证用户名密码是否正确
        if (!$user = $this->where($filter)->find()){
            $this->error = '账号错误';
            return false;
        }
        if($user['password'] != hema_hash($data['password'])){
            $this->error = '密码错误';
            return false;
        }
        // 保存登录状态
        Session::set('hema_admin', [
            'user' => $user,
            'is_login' => true,
        ]);
        return true;
    }
    
    /**
     * 更新当前管理员信息
     */
    public function renew(array $data)
    {   
        if ($data['password'] != $data['password_confirm']) {
            $this->error = '确认密码不正确';
            return false;
        }
        $data['password'] = hema_hash($data['password']);
        // 更新管理员信息
        return $this->save($data) !== false;
    }
    
    /**
     * 代理操作
     */
    public function agentAction()
    {
        if($this->status['value'] == 20){
            return $this->save(['status' => 30]) !== false;//设置为代理
        }
        Db::startTrans();// 开启事务
        try {
            $this->save(['status' => 20]);//取消代理
            Applet::where('agent_id',$this->user_id)->update(['agent_id' => 0]);
            User::where('agent_id',$this->user_id)->update(['agent_id' => 0]);
            DivideAccount::where('agent_id',$this->user_id)->delete();
            Template::where('agent_id',$this->user_id)->delete();
            Apply::where('agent_id',$this->user_id)->delete();
            Record::where('user_id',$this->user_id)->delete();
			Db::commit();
            return true;
        } catch (\Exception $e) {
            Db::rollback();
        }
        return false;
		
	}
}
